package com.shuda.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuda.business.user.entity.UserEntity;
import com.shuda.business.user.entity.UserRoleEntity;
import com.shuda.business.user.mapper.UserMapper;
import com.shuda.business.user.mapper.UserRoleMapper;
import com.shuda.business.user.service.UserService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.result.ResultCode;
import com.shuda.common.security.SecurityUtils;
import com.shuda.common.utils.PageResult;
import com.shuda.common.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public PageResult<UserEntity> getUserPage(PageDTO pageDTO, QueryWrapper<UserEntity> queryWrapper) {
        Page<UserEntity> page = PageUtils.buildPage(pageDTO);
        Page<UserEntity> userPage = userMapper.selectPage(page, queryWrapper);
        return PageUtils.buildPageResult(userPage);
    }

    @Override
    public UserEntity getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public UserEntity getByUsername(String username) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUser(UserEntity user) {
        // 检查用户名是否已存在
        if (getByUsername(user.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 设置默认密码
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            user.setPassword(passwordEncoder.encode("123456"));
        } else {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        
        // 设置默认状态
        if (user.getStatus() == null) {
            user.setStatus("active");
        }
        
        // 设置创建信息
        user.setCreateTime(LocalDateTime.now());
        user.setCreateBy(SecurityUtils.getCurrentUserId());
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(SecurityUtils.getCurrentUserId());
        user.setDeleted(0);
        user.setTenantId(SecurityUtils.getCurrentTenantId());
        
        userMapper.insert(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserEntity user) {
        // 检查用户是否存在
        UserEntity existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 如果更新密码，需要加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 不更新密码
            user.setPassword(null);
        }
        
        // 设置更新信息
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(SecurityUtils.getCurrentUserId());
        
        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        UserEntity user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 逻辑删除
        user.setDeleted(1);
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(SecurityUtils.getCurrentUserId());
        userMapper.updateById(user);
        
        // 删除用户角色关联
        userRoleMapper.deleteByUserId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(List<Long> ids) {
        for (Long id : ids) {
            deleteUser(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserStatus(Long id, String status) {
        UserEntity user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(SecurityUtils.getCurrentUserId());
        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long id, String password) {
        UserEntity user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        user.setPassword(passwordEncoder.encode(password));
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(SecurityUtils.getCurrentUserId());
        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoles(Long userId, List<Long> roleIds) {
        // 检查用户是否存在
        UserEntity user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 删除原有角色关联
        userRoleMapper.deleteByUserId(userId);
        
        // 批量插入新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            userRoleMapper.batchInsert(userId, roleIds);
        }
    }

    @Override
    public List<Long> getUserRoles(Long userId) {
        return userRoleMapper.selectRoleIdsByUserId(userId);
    }
}